package cn.cstech.aijia.sns.weibo;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;

import com.sina.weibo.sdk.api.ImageObject;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WebpageObject;
import com.sina.weibo.sdk.api.WeiboMessage;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.api.share.BaseRequest;
import com.sina.weibo.sdk.api.share.IWeiboHandler.Response;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.SendMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.SendMultiMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.constant.WBConstants;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.exception.WeiboShareException;
import com.sina.weibo.sdk.net.AsyncWeiboRunner;
import com.sina.weibo.sdk.net.RequestListener;
import com.sina.weibo.sdk.net.WeiboParameters;
import com.sina.weibo.sdk.utils.Utility;

import java.util.ArrayList;
import java.util.List;

import cn.cstech.aijia.R;
import cn.cstech.aijia.sns.Constants;
import cn.cstech.aijia.sns.SnsErrorCode;
import cn.cstech.aijia.sns.lsn.OnSnsResponseListener;

public class WeiBoController {
	private String TAG = "WeiBoController";
	private static WeiBoController Instance;
	private IWeiboShareAPI mWeiboShareAPI = null;
	private Context mContext;
	private Activity mActivity;
	

	public WeiBoController(Activity activity) {
		mContext = activity;
		mActivity = activity;
	}

	public void init(Intent intent, Activity activity) {
		mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(activity,
				Constants.WEIBO_APP_ID);
		try {
			Log.e(TAG, "loza-init");
			mWeiboShareAPI.registerApp();
			Log.e(TAG, "loza-init-registerApp");
		} catch (Exception e) {
			e.printStackTrace();
			Log.e(TAG, "loza-init-Exception:"+e);
		}
	}
	
	protected SnsErrorCode getSNSCode(int errCode) {
        switch (errCode) {
        case WBConstants.ErrorCode.ERR_OK:
            return SnsErrorCode.SUCCESS;
        case WBConstants.ErrorCode.ERR_CANCEL:
        	return SnsErrorCode.CANCEL;
        case WBConstants.ErrorCode.ERR_FAIL:
        	return SnsErrorCode.FAILED;
        }
		return null;
	}
	
	public void setResponse(Intent arg0, Response arg1){
		if(mWeiboShareAPI != null) {
			mWeiboShareAPI.handleWeiboResponse(arg0,arg1);
		}
	}

	public static WeiBoController getInstance(Activity activity) {
//		if (Instance == null) {
//			Instance = new WeiBoController(activity);
//		}
		//return Instance; 
		return Instance = new WeiBoController(activity);
	}
	
	public boolean isSupported(){
		return mWeiboShareAPI.isWeiboAppInstalled() && mWeiboShareAPI.isWeiboAppSupportAPI() && mWeiboShareAPI.getWeiboAppSupportAPI() > -1;
	}
	
//	public void setResponse(Intent intent, Response ls){
//		if(mWeiboShareAPI == null){
//			init(intent, ls);
//		}
//		if(mWeiboShareAPI != null) {
//			mWeiboShareAPI.handleWeiboResponse(intent, ls);
//		}
//	}

	private OnSnsResponseListener mOnSnsResponseListener;
	public void sendTextMessage(String title, String content, String pic_path, String pic_url, String webUrl, Bitmap thumb, OnSnsResponseListener lsn) {
		try {
			Log.e(TAG, "loza-sendTextMessage");
			
			mOnSnsResponseListener = lsn;
			// 检查微博客户端环境是否正常，如果未安装微博，弹出对话框询问用户下载微博客户端
//			if (isSupported()) {
//				sendSSOMessage(title, content, pic_path, pic_url, webUrl, thumb, lsn);
//			}else{
				sendSSOMultiMessage(title, content, pic_path, pic_url, webUrl, thumb, lsn);
//			}
				Log.e(TAG, "loza-sendTextMessage+1");
		} catch (WeiboShareException e) {
			e.printStackTrace();
			Log.e(TAG, "loza-exception" + e);
		}
	}
	
	private void sendWeiboTextWithImage(String msg,String picPath){
		WeiboParameters bundle = new WeiboParameters(Constants.WEIBO_APP_ID);
		bundle.put("access_token", AccessTokenKeeper.readAccessToken(mContext).getToken());
		bundle.put("status", msg);
		bundle.put("pic", picPath);
		
		AsyncWeiboRunner a = new AsyncWeiboRunner(mContext);
		a.requestAsync(Constants.URL_UPLOAD_TEXT_IMAGE, bundle, "POST", new RequestListener() {
			@Override
			public void onWeiboException(WeiboException we) {
			}
			
			@Override
			public void onComplete(String response) {
			}
		});
	}
	
	private void sendWeiboTextWithPicUrl(String msg,String picUrl){
		WeiboParameters bundle = new WeiboParameters(Constants.WEIBO_APP_ID);
		bundle.put("access_token", AccessTokenKeeper.readAccessToken(mContext).getToken());
		bundle.put("status", msg);
		bundle.put("url", picUrl);
		AsyncWeiboRunner a = new AsyncWeiboRunner(mContext);
		a.requestAsync(Constants.URL_UPLOAD_TEXT_URL, bundle, "POST", new RequestListener() {
			@Override
			public void onWeiboException(WeiboException we) {
			}
			
			@Override
			public void onComplete(String response) {
			}
		});
		
	}
	
	class AuthDialogListener implements WeiboAuthListener {
		@Override
		public void onComplete(Bundle values) {
			String token = values.getString("access_token");
			String expires_in = values.getString("expires_in");
			String uid = values.getString("uid");
			Oauth2AccessToken accessToken = new Oauth2AccessToken(token,
					expires_in);
			if (accessToken.isSessionValid()) {
				AccessTokenKeeper.writeAccessToken(mContext, accessToken);
			}
		}

		@Override
		public void onCancel() {
		}

		@Override
		public void onWeiboException(WeiboException arg0) {
			
		}
	}
	
	private void sendSSOMessage(String title, String content, String pic_path, String pic_url, String webUrl, Bitmap thumb, OnSnsResponseListener lsn) {
		if (mWeiboShareAPI.isWeiboAppSupportAPI()) {
			int supportApi = mWeiboShareAPI.getWeiboAppSupportAPI();
			if (supportApi >= 10351 /* ApiUtils.BUILD_INT_VER_2_2 */) {
				sendSSOMultiMessage(title, content, pic_path, pic_url, webUrl, thumb, lsn);
			} else {
				sendSSOSingleMessage(title, content, pic_path, pic_url, webUrl, thumb, lsn);
			}
		} 
	}

	private void sendSSOMultiMessage(String title, String content, String pic_path, String pic_url, String webUrl, Bitmap thumb, OnSnsResponseListener lsn) {
		// 1. 初始化微博的分享消息
		WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
		if(title != null){
			weiboMessage.textObject = getTextObj(content);
		}
		if(pic_path != null){
			weiboMessage.imageObject = getImageObj(pic_url);
		}
		// 用户可以分享其它媒体资源（网页、音乐、视频、声音中的一种）
		if(webUrl != null){
			weiboMessage.mediaObject = getWebpageObj(title, content, pic_path, pic_url, webUrl, thumb);
		}
		// 2. 初始化从第三方到微博的消息请求
		SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
		// 用transaction唯一标识一个请求
		request.transaction = String.valueOf(System.currentTimeMillis());
		request.multiMessage = weiboMessage;
		request.packageName ="com.pingan.papd";

        // 3. 发送请求消息到微博，唤起微博分享界面
		AuthInfo authInfo = new AuthInfo(mContext, Constants.WEIBO_APP_ID,
				Constants.WEIBO_REDIRECT_URL, Constants.SCOPE);
		Oauth2AccessToken accessToken = AccessTokenKeeper
				.readAccessToken(mActivity.getApplicationContext());
		String token = "";
		if (accessToken != null) {
			token = accessToken.getToken();
		}
		
        mWeiboShareAPI.sendRequest(mActivity, request, authInfo, token, new WeiboAuthListener() {
            
            @Override
            public void onWeiboException( WeiboException arg0 ) {
            	
            	Log.e(TAG, "loza-WeiboAuthListener-WeiboException"+arg0.toString());
            }
            
            @Override
            public void onComplete( Bundle bundle ) {
                // TODO Auto-generated method stub
                Oauth2AccessToken newToken = Oauth2AccessToken.parseAccessToken(bundle);
                AccessTokenKeeper.writeAccessToken(mActivity.getApplicationContext(), newToken);
//                Toast.makeText(mActivity.getApplicationContext(), "onAuthorizeComplete token = " + newToken.getToken(), 0).show();
                Log.e(TAG, "loza-WeiboAuthListener-onComplete");
            }
            
            @Override
            public void onCancel() {
            	Log.e(TAG, "loza-WeiboAuthListener-onCancel");
            }
        });
	}

	private BaseRequest  mBaseRequest = null;
	private void sendSSOSingleMessage(String title, String content, String pic_path, String pic_url, String webUrl, Bitmap thumb, OnSnsResponseListener lsn) {

		// 1. 初始化微博的分享消息
		// 用户可以分享文本、图片、网页、音乐、视频中的一种
		WeiboMessage weiboMessage = new WeiboMessage();
		if(title != null){
			weiboMessage.mediaObject = getTextObj(content);
		}
		if(pic_url != null){
			weiboMessage.mediaObject = getImageObj(pic_url);
		}
		
		// 用户可以分享其它媒体资源（网页、音乐、视频、声音中的一种）
		if(webUrl != null){
			weiboMessage.mediaObject = getWebpageObj(title, content, pic_path, pic_url, webUrl, thumb);
		}

		 // 2. 初始化从第三方到微博的消息请求
        SendMessageToWeiboRequest request = new SendMessageToWeiboRequest();
        // 用transaction唯一标识一个请求
        request.transaction = String.valueOf(System.currentTimeMillis());
        request.message = weiboMessage;
        request.packageName ="com.pingan.papd";

		// 3. 发送请求消息到微博，唤起微博分享界面
		mWeiboShareAPI.sendRequest(mActivity, request);
	}

	private TextObject getTextObj(String text) {
		if(text == null){
			return null;
		}
		TextObject textObject = new TextObject();
		textObject.text = text;
		return textObject;
	}

	private ImageObject getImageObj(String imageUrl) {
		if(imageUrl == null){
			return null;
		}
		ImageObject imageObject = new ImageObject();
		imageObject.imagePath = imageUrl;
		return imageObject;
	}

	private WebpageObject getWebpageObj(String title, String content, String pic_path, String pic_url, String webUrl, Bitmap thumb) {
		if(webUrl == null){
			return null;
		}
		WebpageObject mediaObject = new WebpageObject();
		mediaObject.identify = Utility.generateGUID();
		mediaObject.title = title;
		mediaObject.description = content;
//
//		// 设置 Bitmap 类型的图片到视频对象里
		if (thumb == null) {
			thumb = BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_launcher);
		}
		mediaObject.setThumbImage(thumb);
		mediaObject.actionUrl = webUrl;
		mediaObject.defaultText = content;
		return mediaObject;
	}
	
	public IWeiboShareAPI getIWeiboShareAPI(){
		return mWeiboShareAPI;
	}
	
	public boolean isAppInstalled(Context context, String packageName) {  
        final PackageManager packageManager = context.getPackageManager();  
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);  
        List<String> pName = new ArrayList<String>();  
        if (pinfo != null) {  
            for (int i = 0; i < pinfo.size(); i++) {  
                String pn = pinfo.get(i).packageName;  
                pName.add(pn);  
            }  
        }  
        return pName.contains(packageName);  
    }

}
